<template>
	<!-- 导航栏 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>内容管理</el-breadcrumb-item>
		<el-breadcrumb-item>FM管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="padding: 15px 0">
		<el-form-item label="文章名">
			<el-input v-model="queryInfo.fmTitle" placeholder="请输入文章名" clearable @clear="queryDataList" />
		</el-form-item>

		<el-form-item label="选择FM分类" style="width: 200px">
			<el-select v-model="queryInfo.sort" placeholder="无" clearable @clear="queryDataList">
				<el-option v-for="item in options" :key="item.value" :label="item.sortName" :value="item.id" />
			</el-select>
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="success" @click="add">新增文章</el-button>
			<el-button type="danger" @click="removeBatch">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 表格数据 -->
	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column fixed="left" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="fmTitle" label="文章名" />
		<el-table-column property="fmPic" label="缩略图">
			<template #default="scope">
				<el-avatar shape="square" size="large" :src="'http://localhost:8080'+scope.row.fmPic"></el-avatar>
			</template>
		</el-table-column>
		<el-table-column property="fmSort.sortName" label="所属分类" />
		<el-table-column property="del" label="状态">
			<template #default="scope">
				<el-tag type="success" v-if="scope.row.del==0">正常</el-tag>
				<el-tag type="danger" v-else>已删除</el-tag>
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="success" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" size="default" default-page-size=5
		layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
		@current-change="handleCurrentChange" />

	<!-- Dialog对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="fmData" label-width="100">
			<el-form-item label="文章标题">
				<el-input v-model="fmData.fmTitle" autocomplete="off" placeholder="请输入文章标题"></el-input>
			</el-form-item>

			<el-form-item label="缩略图">
				<el-upload action="http://localhost:8080/upload" list-type="picture-card" :on-success="handleSuccess"
					:limit="1" :on-preview="handlePictureCardPreview" :file-list="fileList" :on-remove="handleRemove">
					<el-icon
						style="width: 128px; height: 128px; border: 1px dashed #dcdfe6; border-radius: 3px; font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
				<!-- 放大预览组件: 和官网一致 -->
				<el-dialog v-model="dialogVisible">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog>
			</el-form-item>
			<el-form-item label="所属分类">
				<el-select v-model="fmData.sort" placeholder="请选择分类">
					<el-option v-for="item in options" :key="item.value" :label="item.sortName" :value="item.id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">
					确 定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import type { FormInstance, UploadProps } from 'element-plus';
	import { Plus } from '@element-plus/icons-vue';
	import { cloneDeep } from 'lodash-es';

	const queryInfo = reactive({
		id: '',
		fmTitle: '',
		sort: '',
		pageNum: 1,
		pageSize: 5
	})

	const total = ref()

	const dataList = ref([])

	const options = ref([])

	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	const querySortList = () => {
		axios.get('fmSort').then((resp) => {
			if (resp.code == 200) {
				options.value = resp.data
			} else {
				ElMessage.error('FM分类加载失败')
			}
		})
	}

	// 定义查询数据的函数
	const queryDataList = () => {
		axios.get('fm/page', {
			params: queryInfo
		}).then((resp) => {
			if (resp.code == 200) {
				dataList.value = resp.data.list;
				total.value = resp.data.total;
			} else {
				ElMessage.error("数据查询失败")
			}
		})
	}

	// 组件加载完毕，加载数据
	onMounted(() => {
		queryDataList()
		querySortList()
	})

	// 存储复选的数据
	const multipleSelection = ref([])

	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map((item) => {
			return item.id
		})
	}

	/* 每页显示条目数改变 */
	const handleSizeChange = (val : number) => {
		queryDataList()
	}
	/* 页码改变 */
	const handleCurrentChange = (val : number) => {
		queryDataList()
	}

	const title = ref('新增FM')

	const dialogFormVisible = ref(false)

	const fmData = ref({
		del: 0,
		fmPic: "",
		fmSort: { id: '', sortName: "", del: 0 },
		fmTitle: "",
		id: '',
		sort: ''
	})

	const cancle = () => {
		console.log('你点击了取消按钮');
		fmData.value = {
			del: 0,
			fmPic: "",
			fmSort: { id: '', sortName: "", del: 0 },
			fmTitle: "",
			id: '',
			sort: ''
		}
		fileList.value = []
		dialogFormVisible.value=false
	}
	const confirm = () => {
		if (fmData.value.id) {
			axios.put('fm/edit', fmData.value).then((resp) => {
				if (resp.code == 200) {
					ElMessage.success('修改成功')
				} else {
					ElMessage.error('修改失败')
				}
				queryDataList()
				dialogFormVisible.value = false
			})
		} else {
			console.log('你点击了确定按钮');
			axios.post('fm/add', fmData.value).then((resp) => {
				if (resp.code == 200) {
					ElMessage.success('新增成功')
				} else {
					ElMessage.error('新增失败')
				}
				queryDataList()
				dialogFormVisible.value = false
			})
		}
	}

	const add = () => {
		title.value = '新增FM'
		dialogFormVisible.value = true
	}

	const edit = (row) => {
		title.value = '编辑FM'
		dialogFormVisible.value = true
		row.fmClassifyId = row.fmClassifyId + ''
		fmData.value = cloneDeep(row)
		fileList.value = []
		var listView = fmData.value.fmPic;
		if (listView) {
			fileList.value.push({
				name: listView.substr(listView.lastIndexOf('/') + 1),
				url: 'http://localhost:8080' + listView
			})
		}
	}

	// 图片上传
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])

	// 上传成功的回调，res服务器响应的数据
	const handleSuccess = (resp, file) => {
		fmData.value.fmPic = resp.data
		fileList.value = [{
			name: file.name,
			url: 'http://localhost:8080' + resp.data
		}]
	}
	// 图片删除处理
	const handleRemove = () => {
		fmData.value.fmPic = ''
		fileList.value = []
	}
	// 图片预览处理
	const handlePictureCardPreview = (file) => {
		dialogImageUrl.value = file.url
		dialogVisible.value = true
	}

	const remove = (id) => {
		ElMessageBox.confirm(
			'此操作将永久删除文件，是否继续?',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true,
			}).then(() => {
				axios.delete(`fm/${id}`)
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败')
						}
						queryDataList()
					})
			}).catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}
	const removeBatch = () => {
		ElMessageBox.confirm(
			'此操作将永久删除文件，是否继续?',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true,
			}).then(() => {
				axios.delete(`fm?ids=${multipleSelection.value.join(',')}`)
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败')
						}
						queryDataList()
					})
			}).catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}
</script>

<style scoped>
	.el-breadcrumb {
		/* 下划线 */
		border-bottom: 1px solid #eeeeee;
		padding-bottom: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.el-pagination {
		margin-top: 15px;
	}

	/* 修正上传组件样式 */
	:deep(.el-upload--picture-card) {
		width: 128px;
		height: 128px;
		line-height: 128px;
	}

	/* 图片预览样式 */
	:deep(.el-upload-list--picture-card .el-upload-list__item) {
		width: 128px;
		height: 128px;
	}
</style>